#+_+ coding:utf-8 +_+

import tornado.web
import auth
from common import errno
from common import buffer
import storage

class LoginHdl(tornado.web.RequestHandler):
    def get(self):
        token = self.get_argument("token","")
        rst = auth.IsValied(token)
        if rst:
            uid    = auth.GenUID()
            ticket = auth.GenTicket(uid,token)
            if ticket :
                rep = self.success(uid,ticket)
            else :
                rep = self.ticketError()
        else :
            rep = self.tokenError()
        self.write(rep)

    def success(self,uid,ticket):
        storage.uid.UIDTicketPoll.Update(uid,ticket)
        msg = dict(uid=uid,ticket=ticket)
        rep = dict(rst="SUCCESS",msg=msg)
        return buffer.JsonEncode(rep)


    def ticketError(self):
        msg = dict(errno=errno.EAUTH_LOGIN_INVALIED_TOKEN,errmsg=errno.ErrStr(EAUTH_LOGIN_INVALIED_TOKEN))
        rep = dict(rst="FAILED",msg=msg)
        return buffer.JsonEncode(rep)
    
    def tokenError(self):
        msg = dict(errno=errno.EAUTH_LOGIN_UID_ERROR,errmsg=errno.ErrStr(EAUTH_LOGIN_UID_ERROR))
        rep = dict(rst="FAILED",msg=msg)
        return buffer.JsonEncode(rep)
